<template>
  <div class="container">
    <Breadcrumb :items="['menu.cmdb.secret', 'menu.cmdb.secret.list']" />
    <a-card class="general-card" :title="$t('menu.cmdb.secret.list')">
      <a-row style="margin-bottom: 16px">
        <a-col :span="16">
          <a-space>
            <a-button type="primary" @click="handleClick">
              <template #icon>
                <icon-plus />
              </template>
              {{ $t('searchTable.operation.create') }}
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-table
        row-key="id"
        :loading="loading"
        :pagination="pagination"
        :data="renderData"
        :bordered="true"
        @page-change="onPageChange"
      >
        <template #columns>
          <a-table-column title="名称" data-index="data.description">
            <template #cell="{ record }">
              <span>
                <a-link @click="jumpToDetial(record.id)">{{
                  tansferVendor(record.data.description)
                }}</a-link>
              </span>
            </template>
          </a-table-column>
          <a-table-column title="厂商">
            <template #cell="{ record }">
              <span>{{ tansferVendor(record.data.vendor) }}</span>
            </template>
          </a-table-column>
          <a-table-column title="凭证类型">
            <template #cell="{ record }">
              <span>{{ tansferAPIKey(record.data.crendential_type) }}</span>
            </template>
          </a-table-column>
          <a-table-column title="API Key" data-index="data.api_key" />
          <a-table-column title="速率限制" data-index="data.request_rate" />
          <a-table-column title="创建时间">
            <template #cell="{ record }">
              <span>{{ tansferTime(record.create_at) }}</span>
            </template>
          </a-table-column>
          <a-table-column
            :title="$t('searchTable.columns.operations')"
            data-index="operations"
          >
            <template #cell="{ record }">
              <a-button type="text" size="small" @click="updateSecret(record)">
                <template #icon>
                  <icon-edit />
                </template>
              </a-button>
              <a-popconfirm
                content="该删除很危险, 是否确认删除"
                @ok="deleteSecret(record)"
              >
                <a-button
                  :loading="deleteLoading === record.id"
                  type="text"
                  size="small"
                  style="color: red"
                >
                  <template #icon>
                    <icon-delete />
                  </template>
                </a-button>
              </a-popconfirm>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <!-- 创建与修改secret对话框 -->
    <a-modal v-model:visible="visible">
      <template #title> {{ formTitle }} </template>
      <template #footer>
        <a-space>
          <a-button @click="handleCancel">取消</a-button>
          <a-button type="primary" @click="handleSubmit">确定</a-button>
        </a-space>
      </template>
      <a-form ref="formDataRef" :model="formData" @submit="handleSubmit">
        <a-form-item
          field="description"
          label="凭证描述"
          :rules="[
            {
              required: true,
              message: '请输入凭证',
            },
          ]"
        >
          <a-input
            v-model="formData.description"
            placeholder="请输入凭证描述"
          />
        </a-form-item>
        <a-form-item field="vendor" label="厂商">
          <a-radio-group v-model="formData.vendor" type="button">
            <a-radio value="ALIYUN">阿里云</a-radio>
            <a-radio value="TENCENT">腾讯云</a-radio>
            <a-radio value="HUAWEI">华为云</a-radio>
            <a-radio value="AWS">AWS</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item field="crendential_type" label="类型">
          <a-radio-group v-model="formData.crendential_type" type="button">
            <a-radio value="API_KEY">API Key</a-radio>
            <a-radio value="PASSWORD">密码</a-radio>
          </a-radio-group>
        </a-form-item>
        <div v-if="formData.crendential_type === 'API_KEY'">
          <a-form-item
            field="api_key"
            label="API Key"
            :rules="[
              {
                required: true,
                message: '请输入凭证Key',
              },
            ]"
          >
            <a-input v-model="formData.api_key" placeholder="请输入凭证Key" />
          </a-form-item>
          <a-form-item
            field="api_secret"
            label="API Secret"
            :rules="[
              {
                required: true,
                message: '请输入凭证Secret',
              },
            ]"
          >
            <a-input-password
              v-model="formData.api_secret"
              placeholder="请输入凭证Secret"
            />
          </a-form-item>
        </div>
        <div v-else-if="formData.crendential_type === 'PASSWORD'">
          <a-form-item field="address" label="服务地址">
            <a-input v-model="formData.address" placeholder="请输入用户名" />
          </a-form-item>
          <a-form-item field="api_key" label="用户名">
            <a-input v-model="formData.api_key" placeholder="请输入密码" />
          </a-form-item>
          <a-form-item field="api_secret" label="密码">
            <a-input-password
              v-model="formData.api_secret"
              placeholder="请输入凭证Secret"
            />
          </a-form-item>
        </div>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, nextTick, onMounted } from 'vue';
  import useLoading from '@/hooks/loading';
  import { Message } from '@arco-design/web-vue';
  import {
    QUERY_SECRET,
    CREATE_SECRET,
    DELETE_SECRET,
    QuerySecret,
    Secret,
  } from '@/api/cmdb/secret';
  import { Pagination } from '@/types/global';
  import { FormInstance } from '@arco-design/web-vue/es/form';
  import { useRouter, Router } from 'vue-router';

  const { loading, setLoading } = useLoading(true);
  const renderData = ref<Secret[]>([]);
  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
  };
  const pagination = reactive({
    ...basePagination,
  });

  const tansferVendor = (vendor: string) => {
    switch (vendor) {
      case 'TENCENT':
        return '腾讯云';
      case 'ALI_YUN':
        return '阿里云';
      default:
        return vendor;
    }
  };

  const tansferAPIKey = (key: string) => {
    switch (key) {
      case 'API_KEY':
        return 'API Key';
      default:
        return key;
    }
  };

  const tansferTime = (ts: number) => {
    const t = new Date(ts);
    return `${t.getFullYear()}-${t.getMonth()}-${t.getDate()} ${t.getHours()}:${t.getMinutes()}`;
  };

  // 这个部分是后端交互获取数据
  const fetchData = async (
    params: QuerySecret = { page_number: 1, page_size: 20 }
  ) => {
    setLoading(true);
    try {
      basePagination.pageSize = params.page_size;
      basePagination.current = params.page_number;
      const data = await QUERY_SECRET(params);
      renderData.value = data.items;
      pagination.total = data.total;
      pagination.current = params.page_number;
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };

  let router = {};
  onMounted(() => {
    router = useRouter();
  });

  const jumpToDetial = (secretId: string) => {
    // 带查询参数，结果是 /register?plan=private
    (router as Router).push({
      path: '/cmdb/detail_secret',
      query: { id: secretId },
    });
  };

  // 获取组件实例
  // onMounted(() => {
  //   console.log(getCurrentInstance())
  // })

  // ref 2种类型: 1. 响应式变量, 2: 组件对象
  // 变量变量的名称 时可以 组件的Ref绑定
  const formDataRef = ref<FormInstance>();
  // 表单逻辑
  const handleClick = async () => {
    // 显示弹窗
    visible.value = true;

    // 对弹出的数据做清理
    await formDataRef.value?.resetFields();
  };
  const visible = ref(false);
  const formTitle = ref('创建凭证');
  const handleCancel = () => {
    // 显示弹窗
    visible.value = false;
  };

  const formData = reactive({
    description: '',
    vendor: 'TENCENT',
    crendential_type: 'API_KEY',
    address: '',
    api_key: '',
    api_secret: '',
    request_rate: 10,
    allow_regions: ['*'],
  });
  const handleSubmit = async () => {
    // 校验用户参数是否合法
    const res = await formDataRef.value?.validate();

    // 判断res是不是undefine,来判断表单校验是否通过
    if (!res) {
      // 后端交互
      try {
        const resp = await CREATE_SECRET(formData);
        Message.success(`创建凭证${resp.data.description}成功`);
        // 显示弹窗
        visible.value = false;

        // 刷新列表页面
        fetchData();
      } catch (error) {
        Message.error(`${error}`);
      }
    }
  };

  // 更新
  const updateSecret = (row: Secret) => {
    formTitle.value = '编辑凭证';
    // 弹出编辑对话框
    visible.value = true;

    formData.description = row.data.description;
    formData.vendor = row.data.vendor;
    formData.api_key = row.data.api_key;
    formData.api_secret = row.data.api_secret;
  };

  const onPageChange = (current: number) => {
    // 刷新列表页面
    fetchData({ page_number: current, page_size: pagination.pageSize });
  };

  // 删除
  const deleteLoading = ref('');
  const deleteSecret = async (row: Secret) => {
    try {
      // 表示当前处于删除中的行
      deleteLoading.value = row.id;

      await DELETE_SECRET(row.id);
      Message.success(`删除${row.data.description}成功`);

      // 刷新页面
      fetchData({
        page_number: pagination.current,
        page_size: pagination.pageSize,
      });
    } catch (error) {
      Message.error(`${error}`);
    } finally {
      deleteLoading.value = '';
    }
  };

  fetchData();
</script>

<script lang="ts">
  export default {
    name: 'SearchTable',
  };
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
  }
  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }
</style>
